﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Mapa.aspx.cs" Inherits="SITAX.Mapa" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
    <meta charset="utf-8"/>
    <style>
      html, body, #map-canvas {
        height: 100%;
        margin: 0px;
        padding: 0px
      }
    </style>
    <title></title>
    <script src="Scripts/jquery-1.4.1-vsdoc.js"></script>
    <script src="Scripts/jquery-1.4.1.js"></script>
    <script src="Scripts/jquery-1.4.1.min.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true"></script>
    <script>
        // Note: This example requires that you consent to location sharing when
        // prompted by your browser. If you see a blank space instead of the map, this
        // is probably because you have denied permission for location sharing.

        var map;
        var markers = [];
        var emailc = 'emailc';
        var emailp = 'emailp';
        var VemailC;
        var VemailP;
        //var a = 4.6492;
        //var b = -74.062798;
      // var a = 10.44594;
        //var b = -73.24856;
        window.onload = function () {
            VemailC = locationVars(emailc);
            VemailP = locationVars(emailp);
            //alert(VemailC);
           //alert(VemailP);
            // alert(email.innerText);
            initialize();
            //if (VemailC == null) {
            //    //mapa general            
            //    //InitAjaxSetup();
            //    alert("Bien 2");

            //} else {
            //    //mapa especifico
            //    //UbicarPasajero();
            //}
            
        }

        function correccion() {
            if (VemailC == null) {
                //mapa general            
                //InitAjaxSetup();
                alert("Bien 2");

            } else {
                //mapa especifico
                //UbicarPasajero();
            }
        }
        function initialize1() {
            var mapOptions = {
                zoom: 16,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementById('map-canvas'),
                mapOptions);

            // Try HTML5 geolocation
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function (position) {
                    var pos = new google.maps.LatLng(position.coords.latitude,
                                                     position.coords.longitude);

                    var infowindow = new google.maps.InfoWindow({
                        map: map,
                        position: pos,
                        content: 'Location found using HTML5.'
                    });

                    map.setCenter(pos);
                }, function () {
                    handleNoGeolocation(true);
                });
            } else {
                // Browser doesn't support Geolocation
                handleNoGeolocation(false);
            }
        }

        function initialize() {
            //alert('hay esta');
            var mapOptions = {
                zoom: 16,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            //alert("de nuevo");
            map = new google.maps.Map(document.getElementById('map-canvas'),
                mapOptions);
            
            //alert(map);

            // Try HTML5 geolocation
            if (navigator.geolocation) {
                //alert("de nuevo null");
                navigator.geolocation.getCurrentPosition(function (position) {
                    var pos = new google.maps.LatLng(position.coords.latitude,
                                                     position.coords.longitude);
                    //alert("de nuevo null");
                    //var infowindow = new google.maps.InfoWindow({
                    //    map: map,
                    //    position: pos,
                    //    content: 'Mi ubicacion'
                    //});
                    
                    if (VemailC == null) {
                        var marker = new google.maps.Marker({
                            position: pos,
                            map: map,
                            title: 'Mi Ubicacion'
                        });
                        
                        // alert(pos.lat());
                        InitAjaxSetup();
                        ActualizarUbicacion(VemailP, pos);
                    } else {
                        //alert(markers.length.toString());
                        UbicarPasajero();
                        //alert(markers.length.toString());
                        var image = 'Imagenes/taxi1.png';
                        var beachMarker = new google.maps.Marker({
                            position: pos,
                            map: map,
                            title: 'Mi Ubicacion taxi',
                            icon: image
                        });
                        beachMarker.setMap(map);
                       // markers.push(beachMarker);
                        //alert(pos.lat());
                        //alert("Bien 1");
                        //alert(markers.length.toString());
                       // setAllMap();
                       ActualizarUbicacion(VemailC,pos);
                    }

                   // alert("Bien 1");
                   
                    map.setCenter(pos);
                }, function () {
                    handleNoGeolocation(true);
                });
            } else {
                // Browser doesn't support Geolocation
                handleNoGeolocation(false);
            }

        }
        function handleNoGeolocation(errorFlag) {
            if (errorFlag) {
                var content = 'Error: The Geolocation service failed.';
            } else {
                var content = 'Error: Your browser doesn\'t support geolocation.';
            }

            var options = {
                map: map,
                position: new google.maps.LatLng(60, 105),
                content: content
            };

            var infowindow = new google.maps.InfoWindow(options);
            map.setCenter(options.position);
        }
        function Ubicacion(item) {
            if (item.ubicacion.Longitud != null) {

                var mapOptions = {
                    zoom: 16,
                    center: new google.maps.LatLng(item.ubicacion.Latitud, item.ubicacion.Longitud),
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };

                //map = new google.maps.Map(document.getElementById('map-canvas'),
                //    mapOptions);

                var pos = new google.maps.LatLng(item.ubicacion.Latitud, item.ubicacion.Longitud);
                
                //var infowindow = new google.maps.InfoWindow({
                //    map: map,
                //    position: pos,
                //    content: 'Taxi'
                //});
               
                    var image = 'Imagenes/taxi1.png';
                    var beachMarker = new google.maps.Marker({
                        position: pos,
                        map: map,
                        icon: image
                    });
                
                google.maps.event.addListener(beachMarker, 'click', function (event) { DoClick(item.conductor.Email); });// agrego un evento para cada click de de un marcador
                markers.push(beachMarker);//lleno un vector de posiciones de los taxis
            }
        }
        function UbicacionPasajero(item) {
            if (item.ubicacion.Longitud != null) {
               
                var mapOptions = {
                    zoom: 16,
                    center: new google.maps.LatLng(item.ubicacion.Latitud, item.ubicacion.Longitud),
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };

                //map = new google.maps.Map(document.getElementById('map-canvas'),
                //    mapOptions);

                var pos = new google.maps.LatLng(item.ubicacion.Latitud, item.ubicacion.Longitud);

                //var infowindow = new google.maps.InfoWindow({
                //    map: map,
                //    position: pos,
                //    content: 'Taxi'
                //});
                var marker = new google.maps.Marker({
                    position: pos,
                    map: map,
                    title: 'Pasajero'
                })

                marker.setMap(map);
                google.maps.event.addListener(marker, 'click', function (event) { DoClick2(event); });// agrego un evento para cada click de de un marcador
               // markers.push(marker);//lleno un vector de posiciones de los taxis
                //alert(markers.length.toString());
            }
        }
        function DoClick(email) {
            var truthBeTold = window.confirm('Desea tomar el taxi?');
            if (truthBeTold) {
                //window.alert('Welcome to MVP World!');
                //window.open('http://www.google.com');
                window.location.href = 'SolicitarTaxi.aspx?email=' +email;
            }
           // else window.alert('Bye from MVP World!');
        }
        function DoClick2(e) {
            var truthBeTold = window.confirm('Desea regresar?');
            if (truthBeTold) {
                //window.alert('Welcome to MVP World!');
                //window.open('http://www.google.com');
                window.location.href = 'RecogerPasajero.aspx';
            }
            // else window.alert('Bye from MVP World!');
        }
        function setAllMap() {
            for (var i = 0; i < markers.length; i++) {
                markers[i].setMap(map);
                //alert(i.toString());
            }
        }
        function InitAjaxSetup() {
            $.ajax({
                type: "GET",
                url: "/Mapa.aspx/ListaUbicacionesweb",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: true,
                success: function (result) {
                    //alert(JSON.stringify(result.d));
                    var lUbicacion = (typeof result.d) == 'string' ? eval('(' + result.d + ')') : result.d;
                    //$("#dtCliente").html('');
                    $.each(lUbicacion, function (index, item) {
                        Ubicacion(item);
                       //alert(item);
                       // $("#dtCliente").append(item.nombre + " " + item.cedula + "<br/>");
                    });
                    setAllMap();
                },
                error: function (jqXHR, status, error) {
                    alert(error + "-" + jqXHR.responseText);
                }
            });
        }
        function locationVars(vr) {
            var src = String(window.location.href).split('?')[1];
            var vrs = src.split('&');

            for (var x = 0, c = vrs.length; x < c; x++) {
                if (vrs[x].indexOf(vr) != -1) {
                    return decodeURI(vrs[x].split('=')[1]);
                    break;
                };
            };
        }
        function UbicarPasajero() {
            //alert(VemailP);
            var parametro = { email: "'" + VemailP.toString() + "'" };
            $.ajax({
                type: "GET",
                url: "/Mapa.aspx/UbicacionPasajero",
                data: parametro,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: true,
                success: function (result) {
                    var lUbicacion = (typeof result.d) == 'string' ? eval('(' + result.d + ')') : result.d;

                    UbicacionPasajero(lUbicacion);
                   
                },
                error: function (jqXHR, status, error) {
                    alert(error + "-" + jqXHR.responseText);
                }
            });
        }
        function ActualizarUbicacion(e,pos) {
            // alert(lat);
           // alert(pos.lng());
            var parametro = { email: "'" + e.toString() + "'", lat: "'" + pos.lat() + "'", lon: "'" + pos.lng() + "'" };
            $.ajax({
                type: "GET",
                url: "/Mapa.aspx/ActualizarUbicacion",
                data: parametro,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: true,
                success: function (result) {
                    //alert(JSON.stringify(result.d)); // esta linea sirve
                    //var lUbicacion = (typeof result.d) == 'string' ? eval('(' + result.d + ')') : result.d;
                    //alert(result.toString());
                },
                error: function (jqXHR, status, error) {
                    alert(error + "-" + jqXHR.responseText);
                }
            });
        }
         //google.maps.event.addDomListener(window, 'load', initialize);
         //google.maps.event.addDomListener(window, 'load', correccion);
        //initialize;
        setInterval(initialize,3000)//3 seg
    </script>
    
</head>
<body>
    <form id="form1" runat="server">
    <div>
    </div>
    </form>
     <div id="map-canvas">AQUI VA EL MAP</div>
</body>
</html>
